package base.web.tools.result;

import base.web.actions.BaseAction;
import com.opensymphony.xwork2.ActionInvocation;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-6-11
 * Time: 下午2:18
 * To change this template use File | Settings | File Templates.
 */
public class JsonUrlResult extends BaseResult{
    @Override
    protected void doExecute(String s, ActionInvocation actionInvocation) throws Exception {
        ServletContext sc = ServletActionContext.getServletContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("application/json");

        //StrutsRequestWrapper requestWrapper = new StrutsRequestWrapper(request);
        //ResponseWrapper responseWrapper = new ResponseWrapper(response);

        PrintWriter printWriter = response.getWriter();

        BaseAction baseAction = (BaseAction) actionInvocation.getAction();
        printWriter.flush();

        String dataList = "";
        String content = "";

        Object obj = baseAction.getModel().get("dataList");
        Object total = baseAction.getModel().get("total");
        List list = (List) obj;
        Integer totalCount = (Integer) total;
        Map mapData = new HashMap();
        mapData.put("data", list);
        //mapData.put("total", totalCount.intValue());
        dataList = PluSoft.Utils.JSON.Encode(list);

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
        jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
        JSONObject js = JSONObject.fromObject(new HashMap(),jsonConfig);
        js.put("total", totalCount.intValue());
        js.put("data", dataList.toString());
        js.put("code", 1);

        js.write(printWriter);
        System.out.println(dataList);

        /*content = js.toString();

        printWriter.write(content);
        printWriter.flush();
        printWriter.close();
        System.out.println(content);*/

    }
}
